/**
 * useSyncExternalStore
 *
 *      作用：使用外部数据，实现组件间数据共享
 *      语法：
 *        const state = useSyncExternalStore(subscribe, getSnapshot)
 *
 *        1. subscribe - 订阅函数
 *        2. getSnapshot - 获取数据的一个函数
 *        3. state - 状态数据
 *
 *      案例：
 *        1. 创建一个外部数据源，可以取名叫做 store
 *           1.1 该 store 需要确认好 state 数据
 *           1.2 该 store 需要提供一个供组件订阅的函数，subscribe
 *           1.3 该 store 需要提供一个供组件获取 state 数据的函数，getSnapshot
 */

import { useState, useSyncExternalStore } from "react";

import store from "./store";
import { Button } from "antd";

function Hello() {
  const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
  return <h2>Hello - {state.count}</h2>;
}

export default function App() {
  const [show, setShow] = useState(true);
  const state = useSyncExternalStore(store.subscribe, store.getSnapshot);

  console.log("state", state);
  return (
    <div>
      <h1>useSyncExternalStore</h1>
      <p>count: {state.count}</p>
      <p>msg: {state.msg}</p>
      <Button onClick={() => store.dispatch({ type: "INCREMENT" })}>
        增加
      </Button>
      <Button onClick={() => setShow(!show)}>Toggle</Button>

      <hr />
      {show && <Hello />}
    </div>
  );
}
